---

# Ensure a user exists in RabbitMQ with permissions to only publish.
# This is intended to be something most applications can use, but if you need
# more flexibility, just use the rabbitmq_user module directly.
#
# Required parameters:
#
#   - username (str): the username to create in RabbitMQ, which should match the
#                     CN of the certificate.

# See https://www.rabbitmq.com/access-control.html#permissions for details on
# the RabbitMQ permissions configuration.

- name: Validate parameters
  assert:
    that:
    - username != "admin"
    - username != "guest"
    - username != "nagios-monitoring"
    fail_msg: "This user name is reserved"
  tags:
    - config
    - fedora-messaging
    - rabbitmq_cluster

- name: Prepare the topic permissions dict
  set_fact:
    topic_permissions:
      - vhost: "{{ vhost }}"
        read_priv: .*
        write_priv: "{{ sent_topics }}"
  tags:
    - config
    - fedora-messaging
    - rabbitmq_cluster
  when: env == "staging" and sent_topics

- debug:
    msg: "Topic permissions: {{ topic_permissions|default([]) }}"
  tags:
    - config
    - fedora-messaging
    - rabbitmq_cluster
  when: topic_permissions is defined

- name: Create the user in RabbitMQ
  delegate_to: "{{ rabbitmq_server }}"
  community.rabbitmq.rabbitmq_user:
    user: "{{ username }}"
    vhost: "{{ vhost }}"
    read_priv: "^$"  # Publish only, no reading
    write_priv: "amq\\.topic"
    configure_priv: "^$"  # No configuration permissions
    topic_permissions: "{{ topic_permissions|default([]) }}"
    state: present
  tags:
    - config
    - fedora-messaging
    - rabbitmq_cluster
